#include <btl/extra/Gui/QOSGWidget.hpp>
#include <iostream>

namespace btl
{
namespace extra
{
namespace gui
{

QOSGWidget::QOSGWidget(QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags flags) :
   QGLWidget(parent, shareWidget, flags)
{
   _gw = new osgViewer::GraphicsWindowEmbedded(0, 0, width(), height());
   QGLFormat format;
   QGLFormat::setDefaultFormat(format);
   format.setSamples(4);
   format.setSampleBuffers(true);
   setFormat(format);
   setFocusPolicy(Qt::ClickFocus);
   getCamera()->setViewport(new osg::Viewport(0, 0, width(), height()));
   getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width())/static_cast<double>(height()), 1.0f, 10000.0f);
   getCamera()->setGraphicsContext(_gw.get());
   setThreadingModel(osgViewer::Viewer::SingleThreaded);
}

QOSGWidget::~QOSGWidget(void) {}

void QOSGWidget::paintGL(void)
{
   frame();
}

void QOSGWidget::resizeGL(int width, int height)
{
   _gw->getEventQueue()->windowResize(0, 0, width, height);
   _gw->resized(0, 0, width, height);
}

void QOSGWidget::keyPressEvent(QKeyEvent* event)
{
   _gw->getEventQueue()->keyPress((osgGA::GUIEventAdapter::KeySymbol)*(event->text().toAscii().data()));
}

void QOSGWidget::keyReleaseEvent(QKeyEvent* event)
{
   _gw->getEventQueue()->keyRelease((osgGA::GUIEventAdapter::KeySymbol)*(event->text().toAscii().data()));
}

void QOSGWidget::mouseMoveEvent(QMouseEvent* event)
{
   _gw->getEventQueue()->mouseMotion(event->x(), event->y());
}

void QOSGWidget::mousePressEvent(QMouseEvent* event)
{
   int button = 0;
   switch(event->button())
   {
      case(Qt::LeftButton): button = 1; break;
      case(Qt::MidButton): button = 2; break;
      case(Qt::RightButton): button = 3; break;
      case(Qt::NoButton): button = 0; break;
      default: button = 0; break;
   }
   _gw->getEventQueue()->mouseButtonPress(event->x(), event->y(), button);
}

void QOSGWidget::mouseReleaseEvent(QMouseEvent* event)
{
   int button = 0;
   switch(event->button())
   {
      case(Qt::LeftButton): button = 1; break;
      case(Qt::MidButton): button = 2; break;
      case(Qt::RightButton): button = 3; break;
      case(Qt::NoButton): button = 0; break;
      default: button = 0; break;
   }
   _gw->getEventQueue()->mouseButtonRelease(event->x(), event->y(), button);
}

} //namespace gui
} //namespace extra
} //namespace btl
